import store from "@/store";
import video from "@/api/modules/video";
const state = {
  games: [], // 视频游戏列表
  chats: [], // 当前直播间聊天信息列表
  lives: [], // 直播列表,
  currentLive: 0, // 当前直播索引
};

const actions = {
  // 获取游戏列表 isForce 是否强制刷新,否则度缓存
  getGames(context, isForce = false) {
    if (!isForce && store.state.video.games.length > 0) {
      return Promise.resolve(store.state.games);
    } else {
      return video.getGames().then(_ => {
        context.commit("SET_GAMES", _.data.data);
        return _.data.data;
      });
    }
  },
  // 切换直播房间
  changeLiveRoom(context) {
    console.warn("------进入房间了")
    context.commit("SET_CHATS", []);
    getApp().globalData.socket.sendSocketMessage({
      c: "matchChat",
      a: "enter", // enter
      data: {
        id: state.lives[state.currentLive].id
      },
      cb: "video/ENTER"
    })
    return true;
  },
  // 在房间内发送消息
  sendLiveRoomMessage(context, message) {
    getApp().globalData.socket.sendSocketMessage({
      c: "matchChat",
      a: "chat", // enter
      data: {
        id: state.lives[state.currentLive].id,
        message
      },
      cb: "video/CHAT"
    });
  },
  // 获取直播列表
  getLives(context) {
    return video.getHotLives().then(response => {
      context.commit("SET_LIVES", response.data.data);
      return response;
    });
  },
  // 退出直播房间
  leaveLiveRoom(context, roomId) {
    // 清空聊天记录
    context.commit("SET_CHATS", []);
    console.warn("-----离开房间了")
    getApp().globalData.socket.sendSocketMessage({
      c: "matchChat",
      a: "leave", // leave
      data: {
        id: roomId
      },
      cb: ""
    });
  }
};


const mutations = {
  // 设置游戏列表
  SET_GAMES(state, data) {
    state.games = data;
  },
  ENTER(state, data) {
    if (typeof data === "object") {
      state.chats = [...state.chats, ...[{
        type: "enter",
        data: data.user
      }]];
    }
  },
  CHAT(state, data) {
    if (typeof data !== "object") return false;
    uni.$emit("live_danmu", data);
    //let chats = JSON.parse(JSON.stringify(state.chats));
    // 最多显示 30条
    if(state.chats.length > 30){
      state.chats.shift();
    }
    state.chats.push({
      type: "chat",
      data: { ...data.user,
        ...data.data
      }
    });
  },
  // 设置聊天记录
  SET_CHATS(state, data) {
    state.chats = data;
  },
  SET_LIVES(state, data) {
    state.lives = data;
  },
  CHANGE_ROOM(state, current) {
    // 改变索引
    state.currentLive = current;
    // 清空聊天记录
    state.chats = [];
  }
};


export default {
  namespaced: true,
  state,
  actions,
  mutations
};
